﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace SpaceBattle.Graphics
{
    public sealed class Camera
    {
        public static readonly Camera instance = new Camera();
        private float _zoom; // Camera Zoom
        public Matrix _transform; // Matrix Transform
        public Vector2 _pos; // Camera Position
        private float _rotation; // Camera Rotation

        static Camera()
        {
        }

        private Camera()
        {
            _zoom = 1.0f;
            _rotation = 0.0f;
            _pos = Vector2.Zero;
        }
        public static Camera Instance
        {
            get
            {
                return instance;
            }
        }
        public float Zoom
        {
            get { return _zoom; }
            set
            {
                _zoom = value;
                if (_zoom < 0.4f) _zoom = 0.4f;
                else if (_zoom > 1.4f) _zoom = 1.4f;
            } // Negative zoom will flip image
        }

        public float Rotation
        {
            get { return _rotation; }
            set { _rotation = value; }
        }

        // Auxiliary function to move the camera
        public void Move(Vector2 amount)
        {
            _pos += amount;
        }
        // Get set position
        public Vector2 Pos
        {
            get { return _pos; }
            set { _pos = value; }
        }
        public Matrix get_transformation(GraphicsDeviceManager graphicsDevice)
        {
            _transform = Matrix.CreateTranslation(new Vector3(-graphicsDevice.PreferredBackBufferWidth * 0.5f - _pos.X, -graphicsDevice.PreferredBackBufferHeight * 0.5f - _pos.Y, 0)) * Matrix.CreateScale(
                new Vector3((_zoom * _zoom * _zoom),
                (_zoom * _zoom * _zoom), 0))
            * Matrix.CreateRotationZ(_rotation)
               * Matrix.CreateTranslation(new Vector3(
                graphicsDevice.PreferredBackBufferWidth * 0.5f, graphicsDevice.PreferredBackBufferHeight * 0.5f, 0));

            return _transform;
        }



        public Vector2 get_mouse_vpos(GraphicsDeviceManager graph)
        {
            float MouseWorldX = (Mouse.GetState().X - graph.PreferredBackBufferWidth * 0.5f + (graph.PreferredBackBufferWidth * 0.5f + _pos.X) * (float)Math.Pow(_zoom, 3)) /
                  (float)Math.Pow(_zoom, 3);

            float MouseWorldY = ((Mouse.GetState().Y - graph.PreferredBackBufferHeight * 0.5f + (graph.PreferredBackBufferHeight * 0.5f + _pos.Y) * (float)Math.Pow(_zoom, 3))) /
                    (float)Math.Pow(_zoom, 3);

            return new Vector2(MouseWorldX, MouseWorldY);
        }


    }
}
